#!/usr/bin/env bash
# --------------------------------------------------------
# GitLab 内网 webhook 访问修复脚本
# 适用于：GitLab 容器版 (例如 gitlab/gitlab-ce:15.x)
# --------------------------------------------------------

# === 参数区域 ===
GITLAB_CONTAINER=$(docker ps --format '{{.Names}}' | grep -E '^gitlab' | head -n 1)
NETWORK_WHITELIST="['10.0.0.0/8','172.16.0.0/12','192.168.0.0/16','127.0.0.1']"

# === 检查容器是否存在 ===
if [ -z "$GITLAB_CONTAINER" ]; then
  echo "❌ 未找到名为 gitlab 的容器，请确认容器名称。"
  echo "👉 提示：docker ps | grep gitlab"
  exit 1
fi

echo "🔍 检测到 GitLab 容器：$GITLAB_CONTAINER"
echo "🚀 开始修复 WebHook 内网访问权限..."

# === 在容器内执行 Ruby 控制台命令 ===
docker exec -i "$GITLAB_CONTAINER" gitlab-rails runner "
begin
  s = ApplicationSetting.last
  s.update_column(:allow_local_requests_from_web_hooks_and_services, true)
  s.update_column(:allow_local_requests_from_system_hooks, true)
  s.update_column(:outbound_local_requests_whitelist, $NETWORK_WHITELIST)
  puts '✅ 已成功修改 GitLab WebHook 内网访问策略'
  puts '   - WebHook + SystemHook 均允许访问内网'
  puts '   - 允许网段: #{$NETWORK_WHITELIST}'
rescue => e
  puts \"❌ 修改失败: \#{e.message}\"
end
"

# === 重启 GitLab 容器 ===
echo "🔄 重启 GitLab 容器中..."
docker exec "$GITLAB_CONTAINER" gitlab-ctl restart

echo "✅ 修复完成！"
echo "📍 请打开后台验证：/admin/application_settings/network"
echo "   确认 WebHook 和 SystemHook 已允许内网访问。"